﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;

namespace ZPod.MTG.WebServer
{
	public static class ServiceHostHelper
	{
		private static Dictionary<Type, ServiceHost> _hostedServices;

		static ServiceHostHelper()
		{
			_hostedServices = new Dictionary<Type, ServiceHost>();
		}

		public static void HostService(Type serviceType)
		{
			lock (_hostedServices)
			{
				var host = new ServiceHost(serviceType);
				host.Open();
				_hostedServices.Add(serviceType, host);
			}
		}

		public static void HostService(Type serviceType, Type contractType, Uri address)
		{
			lock (_hostedServices)
			{
				var baseAddress = new Uri(String.Format("{0}://{1}/", address.Scheme, address.Authority));
				
				var host = new ServiceHost(serviceType, baseAddress);
				
				var endPoint = host.AddServiceEndpoint(contractType.FullName, new BasicHttpBinding(), address);
				
				ServiceMetadataBehavior metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>( );
				if(metadataBehavior == null)
				{
				   metadataBehavior = new ServiceMetadataBehavior( );
				   host.Description.Behaviors.Add(metadataBehavior);
				}
				host.AddServiceEndpoint(
					typeof(IMetadataExchange),
					new CustomBinding(new HttpTransportBindingElement()),
					"MEX");

				host.Open();
				_hostedServices.Add(serviceType, host);
			}
		}

		public static void StopService(Type serviceType)
		{
			lock (_hostedServices)
			{
				if (_hostedServices.ContainsKey(serviceType))
				{
					_hostedServices[serviceType].Close();
					_hostedServices.Remove(serviceType);
				}
			}
		}
	}
}
